<?php

// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | create by allen.qiang
// +----------------------------------------------------------------------

/**
 * 用户ajax类
 * @package  ajax
 * @subpackage  backend
 * @author   create by allen.qiang
 */
quanli_require('module/base/system/sysUser.class.php');

class ajax_userList {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && is_numeric($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch ($_REQUEST['operFlg']) {

                case 1:
                    $this->searchUserList();
                    break;

                case 2:
                    $this->editUser();
                    break;

                case 6:
                    $this->userPersonnel();
                    break;
                case 100:

                    if (!isset($_REQUEST['act']) || !in_array($_REQUEST['act'], array('del', 'edit', 'change'))) {
                        returnJsonData('参数错误');
                    }
                    if ($_REQUEST['act'] == 'edit') {

                        $this->edit();//新增、修改用户

                    } else if ($_REQUEST['act'] == 'del') {

                        $this->deleteUser();//删除用户

                    } else if ($_REQUEST['act'] == 'change') {

                        $this->changeUse();//启用、禁用用户

                    }

                    break;
            }
        } else {

            $this->toReturn('参数错误');
        }
    }

    /**
     * 返回信息
     * @param string $message
     * @param int $code
     * @param mixed $data
     */
    private function toReturn($message, $code = 400, $data = '') {

        die(json_encode(array('code' => $code, 'message' => $message, 'data' => $data)));
    }

    /**
     * 个人设置
     */
    private function userPersonnel() {

        global $G_PGLOB;

        if (!isset($_REQUEST['trueName'], $_REQUEST['email'], $_REQUEST['userID'], $_REQUEST['userPwd'], $_REQUEST['repeatPwd']) || empty($_REQUEST['userID'])) {
            $this->toReturn('参数错误');
        }

        //实例化公共类
        $commHandler = new commHandler();

        if (empty($_REQUEST['trueName'])) {
            $this->toReturn('用户姓名不能为空');
        }

        if (!empty($_REQUEST['userPwd'])) {

            if (!$commHandler->isPwd($_REQUEST['userPwd'])) {
                $this->toReturn('输入的密码格式错误');
            }
            if ($_REQUEST['userPwd'] != $_REQUEST['repeatPwd']) {
                $this->toReturn('两次输入的密码不一致');
            }
        }

        if (!$commHandler->isEmail($_REQUEST['email'])) {
            $this->toReturn('电子邮件不能为空或格式错误');
        }

        try {

            $user_obj = new entity('user_master');
            $user_obj->userID = $_REQUEST['userID'];
            if (!$G_PGLOB->DBCA->fetch($user_obj)) {
                throw new Exception('用户信息没有找到', 404);
            }
            $user_obj->trueName = $_REQUEST['trueName'];
            if (!empty($_REQUEST['userPwd'])) {
                $user_obj->userPwd = md5($_REQUEST['userPwd']);
            }
            $user_obj->email = $_REQUEST['email'];
            $G_PGLOB->DBCA->save($user_obj);

            $this->toReturn('个人信息修改成功', 200);
        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                $this->toReturn($e->getMessage(), $e->getCode());
            } else {
                error_log($e->getMessage());
                $this->toReturn('系统错误', 500);
            }
        }
    }

    /**
     * 查询用户信息
     */
    private function searchUserList() {

        global $G_PGLOB;

        //实例用户类
        $sysUser = new sysUser($G_PGLOB->DBCA);

        //查询用户信息
        $user_array = $sysUser->searchUserInfo($_REQUEST);

        //组织返回的数据
        $result_array = array(
            'page' => $_REQUEST['page'],
            'total' => $_REQUEST['count'],
            'rows' => array()
        );

        if ($user_array) {

            $edit_permission = $G_PGLOB->has_permission(8);

            foreach ($user_array as &$user) {

                if ($user['useFlg']) {
                    $use_name = '启用';
                    $useFlg = 0;
                } else {
                    $use_name = '禁用';
                    $useFlg = 1;
                }

                if ($edit_permission) {

                    $operate = '<a href="javascript: void(0);" onclick="user.edit(\'' . $user['userID'] . '\');">修改</a>&nbsp;&nbsp;';
                    $operate .= '<a href="javascript: void(0);" onclick="user.role(\'' . $user['userID'] . '\');">角色</a>';
                    $result_array['rows'][] = array(
                        'id' => $user['userID'],
                        'cell' => array(
                            $operate,
                            $user['userID'],
                            $user['trueName'],
                            $user['email'],
                            empty($user['extend_3']) ? '' : $user['extend_3'],
                            '<a href="javascript: void(0);" onclick="user.change.confirm(\'' . $user['userID'] . '\', ' . $useFlg . ')">' . $use_name . '</a>'
                        )
                    );
                } else {

                    $result_array['rows'][] = array(
                        'id' => $user['userID'],
                        'cell' => array(
                            $user['userID'],
                            $user['trueName'],
                            $user['email'],
                            empty($user['extend_3']) ? '' : $user['extend_3'],
                            $use_name
                        )
                    );
                }
            }
        }

        echo json_encode($result_array);
    }

    /**
     * 新增或修改用户信息
     */
    private function edit() {

        global $G_PGLOB;

        //加载角色类
        quanli_require('module/base/system/sysRole.class.php');

        //实例用户类
        $sysUser = new sysUser($G_PGLOB->DBCA);

        $result_data = array();
        /**
         * =============================
         * 查询用户信息
         * =============================
         */
        if (isset($_REQUEST['userID']) && !empty($_REQUEST['userID'])) {

            //查询用户信息
            $arg_array = array(
                'userID' => $_REQUEST['userID']
            );
            $user_array = $sysUser->searchUserInfo($arg_array);
            if (!$user_array) {
                $this->toError('用户信息没有找到');
            }


            $result_data['editData'] = $user_array;
            $result_data['cityID'] = explode(",",$user_array[0]['cityID']);
            $result_data['distributionID'] = explode(",",$user_array[0]['distributionID']);

            //查询用户已有的角色信息
            $user_role_array = $sysUser->searchUserRole($_REQUEST['userID']);
            foreach ($user_role_array as $item) {
                $result_data['user_role'][] = $item;
            }
        }

          echo json_encode($result_data);
    }

    /**
     * 保存用户信息
     */
    private function editUser() {

        global $G_PGLOB;

        //把得到的城市，配送站数组从新组装成类似（1,2,3）的字符串
        $city_str = "";
        $distribution_str = "";
        $city_str = implode(",",$_REQUEST['cityID']);
        $distribution_str = implode(",",$_REQUEST['distributionID']);
        $_REQUEST['cityID'] = $city_str;
        $_REQUEST['distributionID'] = $distribution_str;

        //实例用户类
        $sysUser = new sysUser($G_PGLOB->DBCA);

        //新增或修改用户信息
        $_REQUEST['operator'] = $G_PGLOB->currentUserID;
        $result_array = $sysUser->editUser($_REQUEST);

        echo json_encode($result_array);
    }

    /**
     * 启用或禁用用户
     */
    private function changeUse() {

        global $G_PGLOB;

        //实例化用户类
        $sysUser = new sysUser($G_PGLOB->DBCA);

        //启用或禁用用户
        $result_array = $sysUser->changeUserUse($_REQUEST);

        echo json_encode($result_array);
    }
    
    /**
     * 删除用户
     */
    private function deleteUser() {

        if (!isset($_REQUEST['user_arry']) || !is_array($_REQUEST['user_arry'])) {
            $this->toReturn('参数错误');
        }

        global $G_PGLOB;

        //实例化用户类
        $sysUaer = new sysUser($G_PGLOB->DBCA);

        $result_array = $sysUaer->deleteUser($_REQUEST['user_arry']);

        echo json_encode($result_array);
    }

}
